package happy.diandiankong.api.resource;

import com.facepp.http.HttpRequests;
import com.facepp.http.PostParameters;
import com.google.common.collect.ImmutableMap;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import happy.diandiankong.api.db.GroupDao;
import happy.diandiankong.api.db.UserDao;
import happy.diandiankong.api.model.Groups;
import happy.diandiankong.api.util.IdUtil;
import org.skife.jdbi.v2.DBI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Random;

import static happy.diandiankong.api.constant.Constants.GROUP_NAME;

/**
 * Title.
 * <p>
 * Description.
 *
 * @author Bill Lv {@literal <billcc.lv@hotmail.com>}
 * @version 1.0
 * @since 2016-10-30
 */
@Path("/api/user")
@Produces(MediaType.APPLICATION_JSON)
@Api("/user")
public class UserResource {
    static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class);
    static final String[] SUGGESTIONS = new String[]{
            "lvchao", "keyuchang", "zhangweijie", "huzi"
    };

    final DBI dbi;

    public UserResource(DBI dbi) {
        this.dbi = dbi;
    }

    @POST
    @Path("/id/generate")
    @ApiOperation("generate uid")
    public Response generateUid() throws Exception {
        try (GroupDao groupDao = dbi.open(GroupDao.class);
             UserDao userDao = dbi.open(UserDao.class)) {
            final Groups group = groupDao.findByName(GROUP_NAME);
            if (group == null) {
                return Response.ok(ImmutableMap.of("code", -1, "message", "pls init group first")).build();
            }
            int idx = new Random().nextInt(SUGGESTIONS.length);
            String username = (SUGGESTIONS[idx]);
            final long uid = IdUtil.generateId();
            userDao.insert(uid, username, group.getId());
            return Response.ok(
                    ImmutableMap.of("code", 0, "message", "success", "result", ImmutableMap.of("uid", String.valueOf(uid))))
                    .build();
        }
    }

    @POST
    @Path("/group/init")
    @ApiOperation("init group")
    public Response initGroup() throws Exception {
        try (GroupDao groupDao = dbi.open(GroupDao.class)) {
            final Groups group = groupDao.findByName(GROUP_NAME);
            if (group == null) {
                HttpRequests httpRequests = new HttpRequests("79703d127720b84da26fa4690008d27a", "7Rd2wSbmj0bsBcqpwOenFJDWLkmvLt8W", true, true);
                System.out.println("\ngroup/create");
                System.out.println(httpRequests.groupCreate(new PostParameters().setGroupName(GROUP_NAME)));
                groupDao.insert(IdUtil.generateId(), GROUP_NAME);
            }
        }
        return Response.ok(ImmutableMap.of("code", 0, "message", "success")).build();
    }

}
